<template>
  <div class="register-page">
    <!-- 审核中状态展示 -->
    <div class="review-status" v-if="showReviewStatus">
      <img 
        :src="formData.examine === '0' ? require('@/assets/img/reviewing.png' ): require('@/assets/img/review_refused.png')" 
        :alt="formData.examine === '0' ? '审核中' : '审核未通过'" 
      />
      <template v-if="formData.examine === '0'">
        <p class="status-text">您的注册申请正在审核中，请耐心等待</p>
      </template>
      <template v-else>
        <p class="status-text">您的注册申请未通过审核</p>
        <p class="reject-reason" v-if="formData.reasonForReview">
          <span class="reason-label">未通过原因：</span>
          <span class="reason-content">{{ formData.reasonForReview }}</span>
        </p>
        <!-- 重新申请按钮 -->
        <div class="reapply-btn" @click="handleReapply">
          <i class="el-icon-refresh-right"></i>
          <span>重新申请</span>
        </div>
      </template>
    </div>

    <!-- 表单区域 -->
    <div class="form-content" :class="{
      'is-reviewing': showReviewStatus && formData.examine === '0',
      'is-rejected': showReviewStatus && formData.examine === '2'
    }">
      <!-- 账号信息 -->
      <div class="form-section">
        <div class="section-title">账号信息</div>
        <div class="info_cell" :class="{ 'has-error': phoneError }">
          <img src="@/assets/img/icon_phone number@2x.png" alt="" />
          <input 
            placeholder="* 请输入手机号" 
            v-model="formData.phone" 
            maxlength="11" 
            type="number"
            style="width: calc(100% - 9rem)"
            @blur="validatePhone" 
          />
          <div class="del">
            <img src="@/assets/img/delete@2x.png" alt="" v-if="formData.phone.length > 0" @click="emptyField('phone')" />
          </div>
          <span 
            class="query-tag" 
            @click="handleQuery"
            :class="{ 'is-loading': querying }"
          >
            <i class="el-icon-loading" v-if="querying"></i>
            <span>查询是否注册</span>
          </span>
          <div class="error-message" v-if="phoneError">{{ phoneError }}</div>
        </div>

        <!-- <div class="info_cell info_cell_code">
          <img src="@/assets/img/icon_captcha@2x.png" alt="" />
          <input 
            placeholder="* 请输入验证码" 
            v-model="formData.code" 
            @input="changeauthCd" 
            maxlength="6" 
            type="number"
            style="width: calc(100% - 8.9375rem)"
          />
          <div class="del">
            <img src="@/assets/img/delete@2x.png" alt="" v-if="formData.code.length > 0" @click="emptyField('code')" />
          </div>
          <span @click="getCode" v-if="!sending" class="span1 code-btn">获取验证码</span>
          <span v-else class="span2">重新发送({{ time }})</span>
        </div> -->

        <div class="info_cell">
          <img src="@/assets/img/icon_password@2x.png" alt="" />
          <input placeholder="* 请输入密码长度至少8位" v-model="formData.password" type="password" />
          <div class="del">
            <img src="@/assets/img/delete@2x.png" alt="" v-if="formData.password.length > 0" @click="emptyField('password')" />
          </div>
        </div>
      </div>

      <!-- 基本信息 -->
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <div class="info_cell">
          <input placeholder="* 姓名" v-model="formData.name" type="text" />
          <div class="del">
            <img src="@/assets/img/delete@2x.png" alt="" v-if="formData.name.length > 0" @click="emptyField('name')" />
          </div>
        </div>

        <div class="info_cell" :class="{ 'has-error': formErrors.gender }">
          <el-select 
            v-model="formData.gender" 
            placeholder="* 请选择性别"
            class="gender-select"
          >
            <el-option label="男" value="男">
              <div class="gender-option">
                <span>男</span>
              </div>
            </el-option>
            <el-option label="女" value="女">
              <div class="gender-option">
                <span>女</span>
              </div>
            </el-option>
          </el-select>
          <div class="error-message" v-if="formErrors.gender">{{ formErrors.gender }}</div>
        </div>

        <div class="info_cell" :class="{ 'has-error': formErrors.college }">
          <el-select 
            v-model="selectedCollege" 
            placeholder="* 请选择学院"
            class="college-select"
            filterable
            @change="handleCollegeChange"
          >
            <el-option
              v-for="item in collegeOptions"
              :key="item.dictId"
              :label="item.dictName"
              :value="item.dictName"
            >
              <span class="college-option">{{ item.dictName }}</span>
            </el-option>
          </el-select>
          <div class="error-message" v-if="formErrors.college">
            {{ formErrors.college }}
          </div>
        </div>
      </div>

      <!-- 学习经历 -->
      <div class="form-section">
        <div class="section-title">学习经历</div>
        <div class="info_cell date-cell">
          <span class="label"><span class="required">*</span>入学年份</span>
          <input 
            type="number" 
            v-model="formData.admissionYear"
            placeholder="如：2014"
            maxlength="4"
            @input="validateYear('admissionYear')"
            @blur="validateYear('admissionYear')"
          />
          <div class="error-message" v-if="formErrors.admissionYear">{{ formErrors.admissionYear }}</div>
        </div>

        <div class="info_cell date-cell">
          <span class="label"><span class="required">*</span>毕业年份</span>
          <input 
            type="number" 
            v-model="formData.graduationYear"
            placeholder="如：2018"
            maxlength="4"
            @input="validateYear('graduationYear')"
            @blur="validateYear('graduationYear')"
          />
          <div class="error-message" v-if="formErrors.graduationYear">{{ formErrors.graduationYear }}</div>
        </div>

        <div class="info_cell">
          <input placeholder="* 专业" v-model="formData.major" type="text" />
        </div>

        <div class="info_cell">
          <input 
            placeholder="* 班级（格式：入学年份+本/硕/博+班级号，如：2014本1）" 
            v-model="formData.classNo" 
            type="text"
            @input="validateClass"
            @blur="validateClass"
          />
          <div class="error-message" v-if="formErrors.classNo">{{ formErrors.classNo }}</div>
          <div class="helper-text" v-if="!formErrors.classNo">
            正确格式示例：2014本1、2014硕1、2014博1
          </div>
        </div>
      </div>

      <!-- 联系方式 -->
      <div class="form-section">
        <div class="section-title">联系方式</div>
        <div class="info_cell" :class="{ 'has-error': formErrors.socialMediaPlatform }">
          <el-select 
            v-model="formData.socialMediaPlatform" 
            placeholder="* 选择常用联系类型"
            class="contact-type-select"
          >
            <el-option
              v-for="option in contactOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            >
              <span class="contact-option">{{ option.label }}</span>
            </el-option>
          </el-select>
          
          <div class="error-message" v-if="formErrors.socialMediaPlatform">
            {{ formErrors.socialMediaPlatform }}
          </div>
        </div>

        <div class="info_cell">
          <input placeholder="* 社交账号" v-model="formData.socialMediaAccount" type="text" />
        </div>

        <div class="info_cell">
          <input placeholder="* 联系电话" v-model="formData.contactInfo" type="text" />
        </div>

        <div class="info_cell" :class="{ 'has-error': emailError }">
          <input 
            placeholder="* 邮箱" 
            v-model="formData.email" 
            type="email" 
            @blur="validateEmail"
            @input="handleEmailInput"
            maxlength="50"
          />
          <div class="del">
            <img 
              src="@/assets/img/delete@2x.png" 
              alt="" 
              v-if="formData.email.length > 0" 
              @click="emptyField('email')" 
            />
          </div>
          <div class="error-message" v-if="emailError">{{ emailError }}</div>
        </div>

        <div class="info_cell">
          <input placeholder="* 现居地" v-model="formData.currentResidence" type="text" />
        </div>

        <div class="info_cell">
          <input placeholder="紧急联系人电话" v-model="formData.emergencyContact" type="text" />
        </div>
      </div>

      <!-- 工作信息 -->
      <div class="form-section">
        <div class="show-more" @click="showMoreInfo = !showMoreInfo">
          {{ showMoreInfo ? '收起更多信息' : '完善更多信息' }}
          <i :class="['arrow', showMoreInfo ? 'up' : 'down']"></i>
        </div>

        <div class="more-info" v-if="showMoreInfo">
          <div class="sub-section">
            <div class="sub-title">工作信息</div>
            <div class="info_cell">
              <input placeholder="工作单位" v-model="formData.workUnit" type="text" />
            </div>

            <div class="info_cell">
              <input placeholder="职位" v-model="formData.position" type="text" />
            </div>

            <div class="info_cell direction-select">
              <el-cascader
                v-model="formData.workDirection"
                :options="directionOptions"
                :props="{
                  value: 'value',
                  label: 'label',
                  multiple: true,
                  emitPath: false,
                  lazy: true,
                  lazyLoad: (node, resolve) => handleLazyLoad(node, resolve, 'workDirection')
                }"
                clearable
                collapse-tags
                @change="(value) => handleValueChange(value, 'workDirection')"
                placeholder="请选择工作方向"
              ></el-cascader>
            </div>
          </div>

          <div class="sub-section">
            <div class="sub-title">个人信息</div>
            <div class="info_cell">
              <input placeholder="导师姓名" v-model="formData.advisorName" type="text" />
            </div>

            <div class="info_cell interest-select">
              <el-cascader
                v-model="formData.interests"
                :options="interestOptions"
                :props="{
                  value: 'value',
                  label: 'label',
                  multiple: true,
                  emitPath: false,
                  lazy: true,
                  lazyLoad: (node, resolve) => handleLazyLoad(node, resolve, 'interests')
                }"
                clearable
                collapse-tags
                @change="(value) => handleValueChange(value, 'interests')"
                placeholder="请选择兴趣爱好"
              ></el-cascader>
            </div>

            <div class="info_cell">
              <input placeholder="家乡所在地" v-model="formData.detailedHometown" type="text" />
            </div>

            <div class="info_cell strength-select">
              <el-cascader
                v-model="formData.personalSkill"
                :options="strengthOptions"
                :props="{
                  value: 'value',
                  label: 'label',
                  multiple: true,
                  emitPath: false,
                  lazy: true,
                  lazyLoad: (node, resolve) => handleLazyLoad(node, resolve, 'personalStrengths')
                }"
                clearable
                collapse-tags
                @change="(value) => handleValueChange(value, 'personalStrengths')"
                placeholder="请选择个人擅长"
              ></el-cascader>
            </div>
          </div>

          <div class="sub-section">
            <div class="sub-title">其他信息</div>
            <div class="info_cell">
              <input placeholder="获奖成就" v-model="formData.honorsAchievements" type="text" />
            </div>
          </div>
        </div>
      </div>

      <!-- 注册按钮 -->
      <div class="registerBtn" v-if="!showReviewStatus || formData.examine !== '0'" @click="register">注册</div>
    </div>

    <!-- 添加其他学院输入弹窗 -->
    <el-dialog
      title="请输入学院名称"
      :visible.sync="showOtherCollegeDialog"
      width="90%"
      :close-on-click-modal="false"
      custom-class="other-college-dialog"
    >
      <el-form :model="otherCollegeForm" ref="otherCollegeForm" :rules="otherCollegeRules">
        <el-form-item prop="collegeName">
          <el-input
            v-model="otherCollegeForm.collegeName"
            placeholder="请输入学院名称"
            maxlength="50"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelOtherCollege">取 消</el-button>
        <el-button type="primary" @click="confirmOtherCollege">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { regUser, sendPhoneCode, getLoginUserInfo, getDictValue, getUserInfoByPhone } from "@/api/api";
export default {
  data() {
    return {
      formData: {
        phone: "",
        password: "",
        code: "863760",
        name: "",
        gender: "",
        admissionYear: "",
        graduationYear: "",
        college: "",
        major: "",
        classNo: "",
        contactInfo: "",
        email: "",
        currentResidence: "",
        workUnit: "",
        position: "",
        workDirection: [],
        detailedHometown: "",
        personalStrengths: [],
        honorsAchievements: "",
        socialMediaPlatform: "微信",
        socialMediaAccount: "",
        emergencyContact: "",
        advisorName: "",
        interests: []
      },
      sending: false,
      time: 60,
      myreg: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
      maxDate: new Date().toISOString().split('T')[0],
      phoneError: '',
      emailError: '',
      passwordError: '',
      formErrors: {},
      showMoreInfo: false,
      emailReg: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      isSelectOpen: false,
      contactOptions: [
        { value: '微信', label: '微信' },
        { value: 'QQ', label: 'QQ' },
        { value: '微博', label: '微博' }
      ],
      classRegex: /^(20\d{2})(本|硕|博)([1-9]\d{0,1})$/,
      yearRegex: /^(19|20)\d{2}$/,
      showReviewStatus: false,
      directionOptions: [],
      interestOptions: [],
      strengthOptions: [],
      rules: {
        workDirections: [
          { type: 'array', required: true, message: '请选择工作方向', trigger: 'change' }
        ]
      },
      hasLoadedSecondLevel: false,
      isQueryMode: false,
      querying: false,
      collegeOptions: [],
      selectedCollege: '', // 选择的学院值
      showOtherCollegeDialog: false, // 其他学院输入弹窗显示状态
      otherCollegeForm: {
        collegeName: ''
      },
      otherCollegeRules: {
        collegeName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' },
          { max: 50, message: '学院名称不能超过50个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    // 检查是否有待查询的手机号
    const registerPhone = window.localStorage.getItem("registerPhone");
    if (registerPhone) {
      this.formData.phone = registerPhone;
      this.queryUserInfo();
      // 清除存储的手机号
      window.localStorage.removeItem("registerPhone");
    }
    this.getDirectionOptions();
    this.getInterestOptions();
    this.getStrengthOptions();
    this.getCollegeOptions();
  },
  methods: {
    register() {
      if (!this.validateForm()) {
        this.$vux.toast.text('请完善必填信息');
        return;
      }

      // 重新申请时检查密码是否已填写
      if (!this.formData.password) {
        this.$vux.toast.text('请设置新的密码');
        return;
      }
      
      // 检查密码长度
      if (this.formData.password.length < 8) {
        this.$vux.toast.text('密码长度至少8位');
        return;
      }

      // 创建一个新对象来存储处理后的数据
      const submitData = {
        ...this.formData,
        // 数组已经是选中的值，不需要额外处理
        workDirection: this.formData.workDirection.join(','),
        personalSkill: this.formData.personalStrengths.join(','),
        interests: this.formData.interests.join(',')
      };

      regUser(submitData).then((res) => {
        if (res.code == 200) {
          this.$vux.toast.show("注册申请提交成功，请耐心等待审批");
          this.$router.push({ path: "/login" });
        } else {
          this.$vux.toast.show(res.message);
        }
      });
    },
    getCode() {
      if (!this.myreg.test(this.formData.phone)) {
        alert("手机号格式不正确！");
        return;
      }
      const data = {
        phone: this.formData.phone,
        type: "REG",
      };
      sendPhoneCode(data).then((res) => {
        if (res.code == 200) {
          this.$vux.toast.show("发送成功");
          this.sending = true;
          this.countDown();
        }
      });
    },
    changeauthCd() {
      if (this.formData.code.length > 6) {
        this.formData.code = this.formData.code.slice(0, 6)
      }
    },
    countDown() {
      if (this.time === 0) {
        this.sending = false;
        this.time = 60;
        return;
      } else {
        this.sending = true;
        this.time--;
      }
      setTimeout(() => {
        this.countDown();
      }, 1000);
    },
    emptyField(field) {
      this.formData[field] = "";
      this.formErrors[field] = "";
      if (field === 'phone') this.phoneError = "";
      if (field === 'email') this.emailError = "";
    },
    formatDate(field) {
      if (this.formData[field]) {
        const date = new Date(this.formData[field]);
        this.formData[field] = date.toISOString().split('T')[0];
      }
    },
    validatePhone() {
      if (!this.formData.phone) {
        this.phoneError = '请输入手机号';
        return false;
      }
      if (!this.myreg.test(this.formData.phone)) {
        this.phoneError = '请输入正确的手机号';
        return false;
      }
      this.phoneError = '';
      return true;
    },
    validateEmail() {
      const email = this.formData.email.trim();
      
      if (!email) {
        this.emailError = '请输入邮箱地址';
        return false;
      }

      if (email.length > 50) {
        this.emailError = '邮箱长度不能超过50个字符';
        return false;
      }

      if (!this.emailReg.test(email)) {
        this.emailError = '请输入正确的邮箱格式';
        return false;
      }

      if (email.indexOf('..') !== -1) {
        this.emailError = '邮箱格式不正确，不能包含连续的点';
        return false;
      }

      if (email.indexOf('.@') !== -1 || email.indexOf('@.') !== -1) {
        this.emailError = '邮箱格式不正确，@符号前后不能直接使用点';
        return false;
      }

      const domainPart = email.split('@')[1];
      if (domainPart) {
        if (domainPart.startsWith('-') || domainPart.endsWith('-')) {
          this.emailError = '邮箱域名部分不能以连字符开头或结尾';
          return false;
        }
      }

      this.emailError = '';
      return true;
    },
    handleEmailInput() {
      this.formData.email = this.formData.email.replace(/\s/g, '');
      this.formData.email = this.formData.email.toLowerCase();
    },
    validateForm() {
      this.formErrors = {};
      const requiredFields = {
        phone: '手机号',
        password: '密码',
        name: '姓名',
        gender: '性别',
        admissionYear: '入学年份',
        graduationYear: '毕业年份',
        college: '学院',
        major: '专业',
        classNo: '班级',
        contactInfo: '联系电话',
        email: '邮箱',
        currentResidence: '现居地',
        socialMediaPlatform: '常用联系类型',
        socialMediaAccount: '常用联系方式'
      };

      let isValid = true;
      for (const [field, label] of Object.entries(requiredFields)) {
        if (!this.formData[field]) {
          this.formErrors[field] = `请输入${label}`;
          isValid = false;
        }
      }

      if (!this.validatePhone()) isValid = false;
      if (!this.validateEmail()) isValid = false;
      if (this.formData.password && this.formData.password.length < 8) {
        this.formErrors.password = '密码长度至少8位';
        isValid = false;
      }

      if (!isValid) {
        this.$el.querySelector('input[type="email"]').scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        });
      }

      return isValid;
    },
    toggleSelect() {
      this.isSelectOpen = !this.isSelectOpen;
    },
    
    selectOption(value) {
      this.formData.socialMediaPlatform = value;
      this.isSelectOpen = false;
      this.formErrors.socialMediaPlatform = ''; // 清除错误提示
    },
    
    // 添加点击外部关闭下拉框的方法
    handleClickOutside(event) {
      const select = event.target.closest('.custom-select');
      if (!select) {
        this.isSelectOpen = false;
      }
    },
    resetOptionalFields() {
      const optionalFields = [
        'workUnit', 'position', 'workDirection', 'advisorName',
        'interests', 'detailedHometown', 'personalStrengths',
        'honorsAchievements'
      ];
      
      optionalFields.forEach(field => {
        this.formData[field] = '';
      });
    },
    validateYear(field) {
      const year = this.formData[field];
      if (!year) {
        this.formErrors[field] = '请输入年份';
        return false;
      }
      
      if (!this.yearRegex.test(year)) {
        this.formErrors[field] = '请输入正确的年份格式（1900-2099）';
        return false;
      }
      
      const yearNum = parseInt(year);
      const currentYear = new Date().getFullYear();
      
      // 添加合理的年份范围检查
      if (yearNum < 1900 || yearNum > currentYear) {
        this.formErrors[field] = `年份必须在1900至${currentYear}之间`;
        return false;
      }
      
      // 检查毕业年份是否大于入学年份
      if (field === 'graduationYear' && yearNum <= parseInt(this.formData.admissionYear)) {
        this.formErrors[field] = '毕业年份必须大于入学年份';
        return false;
      }
      
      this.formErrors[field] = '';
      return true;
    },
    validateClass() {
      this.formErrors.classNo = '';
      const classNo = this.formData.classNo;

      if (!classNo) {
        this.formErrors.classNo = '请输入班级';
        return false;
      }

      if (!this.classRegex.test(classNo)) {
        this.formErrors.classNo = '请按格式输入：入学年份+本/硕/博+班级号';
        return false;
      }

      // 检查年份部分是否与入学年份匹配
      const classYear = classNo.substring(0, 4);
      if (this.formData.admissionYear && classYear !== this.formData.admissionYear) {
        this.formErrors.classNo = '班级年份应与入学年份一致';
        return false;
      }

      return true;
    },
    async queryUserInfo() {
      try {
        this.querying = true;
        const res = await getLoginUserInfo({ phone: this.formData.phone });
        if (res.code === 200 && res.data) {
          // 如果审核状态为通过，提示去登录
          if (res.data.examine === '1') {
            this.$vux.confirm.show({
              title: '提示',
              content: '用户注册已通过，请去登录',
              confirmText: '去登录',
              cancelText: '取消',
              onConfirm: () => {
                this.$router.push('/login');
              }
            });
            return;
          }
          
          // 更新表单数据
          this.formData = {
            ...this.formData,
            ...res.data,
            phone: this.formData.phone // 保持手机号不变
          };
          this.showReviewStatus = true;
          
          // 如果是审核中状态，禁用所有输入框
          if (this.formData.examine === '0') {
            this.$nextTick(() => {
              const inputs = document.querySelectorAll('.info_cell input, .info_cell select');
              inputs.forEach(input => {
                input.setAttribute('disabled', 'disabled');
              });
              
              // 禁用获取验证码按钮
              const codeBtn = document.querySelector('.info_cell_code span');
              if (codeBtn) {
                codeBtn.style.pointerEvents = 'none';
                codeBtn.style.opacity = '0.5';
              }
            });
          }
          
          // 显示审核状态
          if (this.formData.examine === '0') {
            this.$vux.toast.show({
              type: 'text',
              text: '您的注册申请正在审核中，请耐心等待',
              position: 'middle',
              width: '80%'
            });
          } else if (this.formData.examine === '2') {
            this.$vux.toast.show({
              type: 'text',
              text: '您的注册申请未通过，原因：' + (res.data.reasonForReview || '未说明'),
              position: 'middle',
              width: '80%'
            });
          }
        }
      } catch (error) {
        console.error('查询用户信息失败:', error);
        this.$vux.toast.show({
          type: 'text',
          text: '查询信息失败，请稍后重试',
          position: 'middle'
        });
      } finally {
        this.querying = false;
      }
    },
    async getDirectionOptions() {
      this.directionOptions = [];  // 初始化为空数组，由懒加载处理
    },
    async getInterestOptions() {
      this.interestOptions = [];
    },
    async getStrengthOptions() {
      this.strengthOptions = [];
    },
    handleValueChange(value, type) {
      console.log(`选中的${type}:`, value);
    },
    async handleLazyLoad(node, resolve, type) {
      const typeMap = {
        workDirection: {
          dictName: "行业领域",
          dictType: "industry_field"
        },
        interests: {
          dictName: "兴趣爱好",
          dictType: "self_hobbies"
        },
        personalStrengths: {
          dictName: "个人擅长",
          dictType: "personally_good"
        }
      };

      try {
        if (node.level === 0) {
          // 加载一级选项
          const res = await getDictValue({
            dictId: "",
            dictName: typeMap[type].dictName,
            dictType: typeMap[type].dictType,
            level: "2"
          });
          
          if (res.code === 200) {
            const nodes = (res.data || []).map(item => ({
              value: item.dictId,
              label: item.dictName,
              leaf: false
            }));
            resolve(nodes);
          }
        } else if (node.level === 1) {
          // 加载二级选项
          const res = await getDictValue({
            dictId: node.value,
            dictName: typeMap[type].dictName,
            dictType: typeMap[type].dictType,
            level: "3"
          });
          
          if (res.code === 200) {
            const nodes = (res.data || []).map(item => ({
              value: item.dictName,
              label: item.dictName,
              leaf: true
            }));
            resolve(nodes);
          }
        }
      } catch (error) {
        console.error(`加载${type}选项失败:`, error);
        this.$message.error(`加载${type}选项失败`);
        resolve([]);
      }
    },
    handleReapply() {
      // 清空审核状态和拒绝原因
      this.formData.examine = '';
      this.formData.rejectReason = '';
      this.showReviewStatus = false;
      // 清空密码，让用户重新填写
      this.formData.password = '';
      
      // 启用表单编辑
      this.$nextTick(() => {
        this.$el.querySelector('.form-content').classList.add('can-edit');
        // 找到密码输入框并添加必填提示
        const passwordInput = this.$el.querySelector('input[type="password"]');
        if (passwordInput) {
          passwordInput.placeholder = '* 请重新设置密码长度至少8位';
        }
      });
      
      // 滚动到表单顶部
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    },
    async getCollegeOptions() {
      try {
        const res = await getDictValue({
          dictId: "",
          dictName: "院系",
          dictType: "department",
          level: "2"
        });
        
        if (res.code === 200 && res.data) {
          // 添加"其他"选项
          this.collegeOptions = [
            ...res.data
          ];
        } else {
          console.error('获取学院列表失败:', res.message);
        }
      } catch (error) {
        console.error('获取学院列表失败:', error);
      }
    },
    async handleCollegeChange(value) {
      if (value === '其他') {
        this.showOtherCollegeDialog = true;
        this.selectedCollege = ''; // 清空选择，等待用户输入
      } else {
        this.formData.college = value;
      }
    },
    cancelOtherCollege() {
      this.showOtherCollegeDialog = false;
      this.otherCollegeForm.collegeName = '';
      this.selectedCollege = '';
      this.formData.college = '';
    },
    async confirmOtherCollege() {
      try {
        await this.$refs.otherCollegeForm.validate();
        this.formData.college = this.otherCollegeForm.collegeName;
        this.selectedCollege = this.otherCollegeForm.collegeName;
        this.showOtherCollegeDialog = false;
        this.otherCollegeForm.collegeName = '';
      } catch (error) {
        // 表单验证失败
        return;
      }
    },
    async handleQuery() {
      // 验证手机号
      if (!this.formData.phone) {
        this.$message.warning('请输入手机号');
        return;
      }
      if (!this.myreg.test(this.formData.phone)) {
        this.$message.warning('请输入正确的手机号');
        return;
      }

      try {
        this.querying = true;
        const res = await getUserInfoByPhone({
          phone: this.formData.phone,
          code: '863760'
        });

        if (res.code === 200) {
          if (res.data) {
            // 根据审核状态处理
            switch(res.data.examine) {
              case '1': // 审核通过
                this.$message({
                  type: 'warning',
                  message: '该手机号已注册，请直接登录',
                  duration: 3000
                });
                setTimeout(() => {
                  this.$router.push('/login');
                }, 1500);
                break;
                
              case '0': // 审核中
                this.showReviewStatus = true;
                this.formData = {
                  ...this.formData,
                  ...res.data,
                  examine: '0'  // 确保审核状态正确设置
                };
                this.$message({
                  type: 'info',
                  message: '您的注册申请正在审核中',
                  duration: 3000
                });
                break;
                
              case '2': // 审核未通过
                this.showReviewStatus = true;
                this.formData = {
                  ...this.formData,
                  ...res.data,
                  examine: '2'  // 确保审核状态正确设置
                };
                break;
                
              default:
                this.$message.error('未知的审核状态');
            }
          } else {
            // 无数据返回，说明未注册
            this.$message({
              type: 'success',
              message: '该手机号未注册，可以继续注册',
              duration: 2000
            });
            // 重置表单数据，只保留手机号
            const phone = this.formData.phone;
            this.formData = {
              ...this.$options.data().formData,
              phone
            };
            this.showReviewStatus = false;
          }
        } else {
          this.$message.error(res.message || '查询失败');
        }
      } catch (error) {
        console.error('查询失败:', error);
        this.$message.error('查询失败，请重试');
      } finally {
        this.querying = false;
      }
    }
  },
  watch: {
    // 监听 formData.college 的变化，同步到 selectedCollege
    'formData.college'(newVal) {
      this.selectedCollege = newVal;
    }
  },
  mounted() {
    // document.addEventListener('click', this.handleClickOutside);
  },
  beforeDestroy() {
    // document.removeEventListener('click', this.handleClickOutside);
  }
};
</script>
<style lang="less" scoped>
.register-page {
  min-height: 100vh;
  width: 100%;
  position: relative;
  background: url('~@/assets/img/login.png') no-repeat center center;
  background-size: cover;
  padding: 20px;
  box-sizing: border-box;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    z-index: 0;
  }

  .review-status,
  .form-content,
  .form-section,
  .info_cell,
  .loginBtn,
  .register,
  .policy,
  .section-title,
  .show-more,
  .more-info,
  .sub-section,
  .sub-title {
    position: relative;
    z-index: 1;
}

.form-section {
    background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
    backdrop-filter: blur(4px);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 3px solid #1989fa;
}

.info_cell {
  background: #fff;
  border-bottom: 1px solid #eee;
  padding: 10px 0;
  position: relative;
  transition: all 0.3s ease;
  &.has-error {
    .span1 {
      top: calc(50% - 11px);  // 调整按钮位置以适应错误提示
    }
  }

  .query-tag {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    padding: 4px 12px;
    font-size: 12px;
    color: #409EFF;
    background: rgba(64, 158, 255, 0.1);
    border: 1px solid rgba(64, 158, 255, 0.2);
    border-radius: 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    transition: all 0.3s;
    white-space: nowrap;

    &:hover {
      color: #fff;
      background: #409EFF;
      border-color: #409EFF;
    }

    &.is-loading {
      pointer-events: none;
      opacity: 0.8;
    }

    .el-icon-loading {
      margin-right: 4px;
      font-size: 12px;
    }
  }

  // 移除原来的查询按钮样式
  .query-btn {
    display: none;
  }
}

.info_cell:last-child {
  border-bottom: none;
  margin-bottom: 15px;
}

.info_cell_code {
  position: relative;
  
  .span1, .span2 {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    height: 30px;
    line-height: 30px;
    padding: 0 15px;
    border-radius: 15px;
    font-size: 14px;
    cursor: pointer;
    background: #409EFF;
    color: #fff;
    text-align: center;
    white-space: nowrap;
  }
  
  .span1.query-btn {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    height: 30px;
    line-height: 30px;
    padding: 0 15px;
    border-radius: 15px;
    font-size: 14px;
    cursor: pointer;
    background: #67C23A;
    color: #fff;
    text-align: center;
    white-space: nowrap;
  }
  
  .span2 {
    background: #909399;
    cursor: not-allowed;
  }
  
  input {
    padding-right: 120px !important;
  }
}

.info_cell input {
  border: none;
  width: calc(100% - 3.0625rem);
  padding: 5px 0px;
  font-size: 0.9375rem;
  outline: none;
}

.info_cell img:nth-of-type(1) {
  display: block;
  width: 0.9375rem;
  height: 1.25rem;
  margin-right: 15px;
  object-fit: contain;
}

.info_cell .del {
  width: 1.1875rem;
  height: 1.1875rem;
}

.info_cell .del>img {
  display: block;
  width: 1.1875rem;
  height: 1.1875rem;
}

.notic {
  padding: 1.625rem 0rem;
  text-align: center;
  font-size: 0.75rem;
  color: #949fb4;
}

.notic>span {
  color: #448eff;
}

.registerBtn {
  width: 14.375rem;
  height: 2.75rem;
  background: linear-gradient(90deg,
      rgba(68, 142, 255, 1) 0%,
      rgba(102, 163, 255, 1) 100%);
  border-radius: 0.1875rem;
  text-align: center;
  line-height: 2.75rem;
  color: #fff;
  font-size: 1.125rem;
  margin: 0px auto;
}

select {
  width: 100%;
  border: none;
  outline: none;
  font-size: 0.9375rem;
  padding: 5px 0;
  color: #333;
}

.info_cell input {
  border: none;
  width: calc(100% - 1.1875rem);
  padding: 5px 0px;
  font-size: 0.9375rem;
  outline: none;
}

input::placeholder {
  color: #999;
}

input::placeholder::first-letter {
  color: #ff4d4f;
}

select option:first-child {
  color: #999;
}

select option:first-child::first-letter {
  color: #ff4d4f;
}

input[type="date"] {
  border: none;
  width: calc(100% - 1.1875rem);
  padding: 5px 0px;
  font-size: 0.9375rem;
  outline: none;
  color: #333;
}

input[type="date"]::-webkit-datetime-edit-text,
input[type="date"]::-webkit-datetime-edit-month-field,
input[type="date"]::-webkit-datetime-edit-day-field,
input[type="date"]::-webkit-datetime-edit-year-field {
  color: #333;
}

input[type="date"]::-webkit-calendar-picker-indicator {
  cursor: pointer;
}

input[type="date"]:invalid::-webkit-datetime-edit {
  color: #999;
}

.date-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.date-cell .label {
  flex-shrink: 0;
  margin-right: 10px;
  font-size: 0.9375rem;
  color: #333;
}

.date-cell input[type="date"] {
  flex: 1;
  min-width: 0;
  text-align: right;
}

.required {
  color: #ff4d4f;
  margin-right: 4px;
}

.error-tip {
  position: absolute;
  left: 0;
  bottom: -18px;
  font-size: 12px;
  color: #ff4d4f;
  padding-left: 10px;
}

.info_cell input.error {
  border-bottom: 1px solid #ff4d4f;
}

.show-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
  color: #1989fa;
  font-size: 14px;
  cursor: pointer;
}

.arrow {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-right: 2px solid #1989fa;
  border-bottom: 2px solid #1989fa;
  margin-left: 5px;
  transition: transform 0.3s;
}

.arrow.down {
  transform: rotate(45deg);
}

.arrow.up {
  transform: rotate(-135deg);
}

.more-info {
  margin-top: 0;
}

.sub-section {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.sub-section:first-child {
  margin-top: 15px;
  padding-top: 0;
  border-top: none;
}

.sub-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 3px solid #1989fa;
  display: flex;
  align-items: center;
}

.more-info .info_cell input {
  font-size: 14px;
  color: #333;
}

.more-info .info_cell input::placeholder {
  color: #999;
  font-size: 14px;
}

.gender-select {
  width: 100%;
  
  /deep/ .el-input {
    .el-input__inner {
      border: none;
      border-bottom: 1px solid #dcdfe6;
      border-radius: 0;
      padding-left: 0;
      font-size: 14px;
      height: 40px;
      line-height: 40px;
      
      &:focus {
        border-color: #409EFF;
      }
      
      &::placeholder {
        color: #999;
      }
    }
  }
  
  &.has-error {
    /deep/ .el-input__inner {
      border-color: #ff4d4f;
    }
  }
}

.gender-option {
  display: flex;
  align-items: center;
  padding: 5px 0;
  
  .gender-icon {
    width: 20px;
    height: 20px;
    margin-right: 8px;
    object-fit: contain;
  }
  
  span {
    font-size: 14px;
    color: #606266;
  }
}

/deep/ .el-select-dropdown__item {
  &.selected {
    .gender-option {
      span {
        color: #409EFF;
        font-weight: 500;
      }
    }
  }
  
  &:hover {
    background-color: #F5F7FA;
  }
}

@media screen and (max-width: 768px) {
  .gender-selector {
    padding: 15px !important;
    
    .gender-options {
      /deep/ .el-radio-group {
        gap: 20px;
        
        .el-radio-button {
          .el-radio-button__inner {
            padding: 25px 30px;
            width: 160px;
          }
        }
      }
    }
    
    .gender-content {
      img {
        width: 100px;
        height: 100px;
      }
      
      span {
        font-size: 15px;
      }
    }
  }

  .info_cell_code {
    .span1, .span2 {
      height: 28px;
      line-height: 28px;
      padding: 0 12px;
      font-size: 13px;
      border-radius: 14px;
    }
    
    input {
      padding-right: 120px !important;
    }
  }

  .info_cell {
    .span1.query-btn {
      height: 28px;
      line-height: 28px;
      padding: 0 12px;
      font-size: 13px;
      border-radius: 14px;
    }
  }
}

.direction-select {
  display: flex;
  gap: 10px;
  
  .el-select {
    &:first-child {
      width: 140px;
    }
    
    &:last-child {
      flex: 1;
    }
  }
}

@media screen and (max-width: 768px) {
  .direction-select {
    flex-direction: column;
    gap: 15px;
    
    .el-select {
      width: 100% !important;
    }
  }
}

.direction-select {
  /deep/ .el-cascader {
    width: 100%;
    
    .el-input__inner {
      border: none;
      padding-left: 0;
      font-size: 14px;
      
      &::placeholder {
        color: #999;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .direction-select {
    /deep/ .el-cascader {
      width: 100%;
    }
  }
}

.interest-select {
  /deep/ .el-cascader {
    width: 100%;
    
    .el-input__inner {
      border: none;
      border-bottom: 1px solid #dcdfe6;
      border-radius: 0;
      padding-left: 0;
      font-size: 14px;
      
      &::placeholder {
        color: #999;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .interest-select {
    /deep/ .el-cascader {
      width: 100%;
    }
  }
}

.strength-select {
  /deep/ .el-cascader {
    width: 100%;
    
    .el-input__inner {
      border: none;
      border-bottom: 1px solid #dcdfe6;
      border-radius: 0;
      padding-left: 0;
      font-size: 14px;
      
      &::placeholder {
        color: #999;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .strength-select {
    /deep/ .el-cascader {
      width: 100%;
    }
  }
}

  .form-content {
    &.is-reviewing {
      opacity: 0.6;
      pointer-events: none;
    }
    &.is-rejected {
      opacity: 0.6;
      pointer-events: none;
      
      &.can-edit {
        opacity: 1;
        pointer-events: auto;
      }
    }
  }

  .info_cell input:disabled,
  .info_cell select:disabled {
    background-color: #f5f7fa;
    cursor: not-allowed;
    opacity: 0.7;
  }

  .info_cell_code {
    .span1, .span2 {
      &[disabled] {
        border-color: #ddd;
        color: #999;
        pointer-events: none;
      }
    }
    
    input {
      padding-right: 120px !important;
    }
  }

  .gender-select {
  width: 100%;
    
    /deep/ .el-input {
      .el-input__inner {
        border: none;
        border-bottom: 1px solid #dcdfe6;
        border-radius: 0;
        padding-left: 0;
        font-size: 14px;
        height: 40px;
        line-height: 40px;
        
        &:focus {
          border-color: #409EFF;
        }
        
        &::placeholder {
          color: #999;
        }
      }
    }
    
    &.has-error {
      /deep/ .el-input__inner {
        border-color: #ff4d4f;
      }
    }
  }

  .gender-option {
    display: flex;
    align-items: center;
    padding: 5px 0;
    
    .gender-icon {
      width: 20px;
      height: 20px;
      margin-right: 8px;
      object-fit: contain;
    }
    
    span {
      font-size: 14px;
      color: #606266;
    }
  }

  /deep/ .el-select-dropdown__item {
    &.selected {
      .gender-option {
        span {
          color: #409EFF;
          font-weight: 500;
        }
      }
    }
    
    &:hover {
      background-color: #F5F7FA;
    }
  }

  @media screen and (max-width: 768px) {
    .info_cell {
      margin: 0 1rem;
      width: calc(100% - 2rem);
    }
    
    .loginBtn {
      width: 80%;
      max-width: 14.375rem;
    }
  }

  .reapply-btn {
    margin-top: 20px;
    padding: 10px 25px;
    font-size: 14px;
    border-radius: 4px;
    
    &:hover {
      opacity: 0.9;
    }
  }

  .review-status {
    text-align: center;
    padding: 20px;  // 减小内边距
    background: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    margin-bottom: 20px;
    position: relative;
    z-index: 1;

    img {
      width: 80px;  // 减小图标尺寸
      height: 80px;
      margin-bottom: 15px;
      object-fit: contain;
    }

    .status-text {
      font-size: 16px;
      color: #303133;
      margin-bottom: 12px;
    }

    .reject-reason {
      margin: 12px 0;
      padding: 10px 15px;
      background: #fef0f0;
      border-radius: 4px;
      text-align: left;
      font-size: 14px;
      line-height: 1.5;

      .reason-label {
        color: #f56c6c;
        font-weight: 500;
        margin-right: 8px;
        display: inline-block;
      }
      
      .reason-content {
        color: #666;
        word-break: break-all;
        display: inline-block;
      }
    }

    .reapply-btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 5px;
      color: #409EFF;
      font-size: 14px;
      cursor: pointer;
      padding: 8px 15px;
      margin-top: 15px;
      border-radius: 4px;
      transition: all 0.3s ease;
      background: rgba(64, 158, 255, 0.1);
      
      i {
        font-size: 16px;
      }
      
      &:hover {
        background: rgba(64, 158, 255, 0.2);
        transform: translateY(-1px);
      }
    }
  }

  @media screen and (max-width: 768px) {
    .review-status {
      padding: 15px;
      
      img {
        width: 60px;  // 移动端更小的图标
        height: 60px;
      }

      .status-text {
        font-size: 14px;
        margin-bottom: 10px;
      }

      .reject-reason {
        margin: 10px 0;
        padding: 8px 12px;
        font-size: 13px;
      }

      .reapply-btn {
        font-size: 13px;
        padding: 6px 12px;
        
        i {
          font-size: 14px;
        }
      }
    }
  }
}

.contact-type-select {
  width: 100%;
  
  /deep/ .el-input {
    .el-input__inner {
      border: none;
      border-bottom: 1px solid #dcdfe6;
      border-radius: 0;
      padding-left: 0;
      font-size: 14px;
      height: 40px;
      line-height: 40px;
      
      &:focus {
        border-color: #409EFF;
      }
      
      &::placeholder {
        color: #999;
      }
    }
  }
  
  &.has-error {
    /deep/ .el-input__inner {
      border-color: #ff4d4f;
    }
  }
}

.contact-option {
  font-size: 14px;
  color: #606266;
}

/deep/ .el-select-dropdown__item {
  &.selected {
    .contact-option {
      color: #409EFF;
      font-weight: 500;
    }
  }
  
  &:hover {
    background-color: #F5F7FA;
  }
}

.college-select {
  width: 100%;
  
  /deep/ .el-input {
    .el-input__inner {
      border: none;
      border-bottom: 1px solid #dcdfe6;
      border-radius: 0;
      padding-left: 0;
      font-size: 14px;
      height: 40px;
      line-height: 40px;
      
      &:focus {
        border-color: #409EFF;
      }
      
      &::placeholder {
        color: #999;
      }
    }
  }
  
  &.has-error {
    /deep/ .el-input__inner {
      border-color: #ff4d4f;
    }
  }
}

.college-option {
  font-size: 14px;
  color: #606266;
}

/deep/ .el-select-dropdown__item {
  &.selected {
    .college-option {
      color: #409EFF;
      font-weight: 500;
    }
  }
  
  &:hover {
    background-color: #F5F7FA;
  }
}

.other-college-dialog {
  /deep/ .el-dialog__body {
    padding: 20px;
  }

  /deep/ .el-input__inner {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    height: 40px;
    padding: 0 15px;
  }

  @media screen and (max-width: 768px) {
    width: 90% !important;
    margin-top: 20vh !important;
  }
}

.query-tag {
  &.is-loading {
    .el-icon-loading {
      animation: rotating 2s linear infinite;
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>